package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.MaterialBaseDao;
import com.sugon.dao.MaterialRecordDao;
import com.sugon.entity.MaterialBaseEntity;
import com.sugon.entity.MaterialRecordEntity;
import com.sugon.entity.SysDeptEntity;
import com.sugon.entity.SysMsgEntity;
import com.sugon.modules.sparepart.consts.MaterialBaseProgress;
import com.sugon.modules.sparepart.service.ISparepartStoreManager;
import com.sugon.modules.tools.service.IToolsStorePosManager;
import com.sugon.service.MaterialBaseService;
import com.sugon.service.SysDeptService;
import com.sugon.service.SysMsgService;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.SysMsgType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 领料单Service实现类
 *
 * @author sugon
 * @date 2020-01-08 08:53:20
 */
@Service("materialBaseService")
public class MaterialBaseServiceImpl implements MaterialBaseService {
    @Autowired
    private MaterialBaseDao materialBaseDao;
    @Autowired
    private MaterialRecordDao materialRecordDao;
    @Autowired
    private SysMsgService sysmsgService;
    @Autowired
    private ISparepartStoreManager sparepartStoreManager;
    @Autowired
    private IToolsStorePosManager toolsStorePosManager;
    @Resource
    private SysDeptService deptService;

    @Override
    public MaterialBaseEntity queryObject(String id) {
        return materialBaseDao.queryObject(id);
    }

    @Override
    public List<MaterialBaseEntity> queryList(Map<String, Object> map) {
        return materialBaseDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return materialBaseDao.queryTotal(map);
    }

    @Override
    public int save(MaterialBaseEntity materialBase) {
        materialBase.setId(RandomUtil.randomString(32));
        materialBase.setMaterCode(generateUniqueCode());
        /*
            优先获取申请人所在的车间，如果为空，则从产线所在车间选择
         */
        if (StrUtil.isEmpty(materialBase.getDeptId())) {
            String workshop = ShiroUtils.getWorkshop();
            if (StrUtil.isNotEmpty(workshop)) {
                materialBase.setDeptId(workshop);
            } else {
                String lineCode = materialBase.getLineCode();
                if (StrUtil.isNotEmpty(lineCode)) {
                    SysDeptEntity line = deptService.getByDCode(lineCode);
                    String deptId = line.getParentId();
                    if (StrUtil.isNotEmpty(deptId) && deptId.length() >= 4) {
                        materialBase.setDeptId(deptId.substring(0, 4));
                    }
                }
            }
        }
        // 设置领用人
        if (StrUtil.isEmpty(materialBase.getPicker())) {
            materialBase.setPicker(ShiroUtils.getUserId());
        }
        materialBase.setIsCheck(0);
        materialBase.setIsOk(0);
        materialBase.setDelFlag(1);
        materialBase.setPickDate(new Date());
        if(materialBase.getProgress() == null){
            materialBase.setProgress(MaterialBaseProgress.NEW);
        }
        return materialBaseDao.save(materialBase);
    }

    @Override
    public synchronized String generateUniqueCode(Object object) {
        // 声明当天的入库编码前缀
        String codePrefix = ErmsCodePrefix.SPARE_MATER + DateUtil.format(DateUtil.date(), "yyyyMMdd") + "-";
        String spareUniqueCode = (String) object;
        if (StrUtil.isEmpty(spareUniqueCode)) {
            // 查询当前最新的入库编码
            spareUniqueCode = materialBaseDao.getLastestPartCode(codePrefix);
        }
        // 生成新的唯一编码
        spareUniqueCode = com.sugon.modules.utils.StrUtil.increase(spareUniqueCode, codePrefix, 4, 1);
        // 确保最新生成备件编码不重复
        MaterialBaseEntity pickList = queryByMaterCode(spareUniqueCode);
        if (pickList == null) {
            return spareUniqueCode;
        }
        return generateUniqueCode(spareUniqueCode);
    }

    @Override
    public int update(MaterialBaseEntity materialBase) {
        int rows = materialBaseDao.update(materialBase);
        if (rows > 0) {
            SysMsgEntity msgEntity = new SysMsgEntity();
            String Id = materialBase.getId();
            msgEntity.setDataId(Id);
            msgEntity.setDataUrl("../spare/sparematerialbase.html?Id=" + Id);
            sysmsgService.addApproveItem(ProcessInfoEnum.SPA_CKSP, msgEntity, 0);
        }
        return rows;
    }

    @Override
    public int check(MaterialBaseEntity materialBase) {
        materialBase.setApprover(ShiroUtils.getUserId());
        materialBase.setApproveDate(DateUtil.date());
        int rows = materialBaseDao.update(materialBase);
        if (rows > 0) {
            SysMsgEntity sysMsgEntity = new SysMsgEntity();
            String Id = materialBase.getId();
            sysMsgEntity.setDataId(Id);
            sysMsgEntity.setDataType(ProcessInfoEnum.SPA_CKSP);
            sysMsgEntity.setDataFlag(SysMsgType.DATA_DEL_END);
            sysmsgService.allMsgData(sysMsgEntity);
        }
        return rows;
    }

    /**
     * 领料出库操作
     *
     * @param materialBase 领料单信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int stockOut(MaterialBaseEntity materialBase) {
        int flag = 0;
        // 获取领料清单
        List<MaterialRecordEntity> materialItems = materialRecordDao.queryAll(materialBase.getId());
        Assert.notEmpty(materialItems);
        // 更新领料单状态
        materialBase.setOutDate(DateUtil.date());
        materialBase.setIsOk(1);
        materialBase.setIsCheck(1);
        materialBase.setProgress(MaterialBaseProgress.END_OUTBOUND);
        materialBaseDao.update(materialBase);
        int type = materialBase.getType();
        if (type == 0) {
            // 执行备件出库逻辑
            sparepartStoreManager.stockOut(materialBase, materialItems);
        } else if (type == 1) {
            // 执行工装出库逻辑
            toolsStorePosManager.stockOut(materialBase, materialItems);
        }
        return flag;
    }

    @Override
    public MaterialBaseEntity queryObjectDetail(String id) {
        return materialBaseDao.queryObjectDetail(id);
    }

    @Override
    public int delete(String id) {
        return materialBaseDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return materialBaseDao.deleteBatch(ids);
    }

    @Override
    public MaterialBaseEntity queryByJobCode(Integer materialType, String jobCode) {
        Map<String, Object> param = new HashMap<>();
        param.put("jobCode", jobCode);
        param.put("materialType", materialType);
        List<MaterialBaseEntity> materialBases = materialBaseDao.queryList(param);
        return CollectionUtil.isNotEmpty(materialBases) ? materialBases.get(0) : null;
    }

    @Override
    public MaterialBaseEntity queryByMaterCode(String materCode) {
        Map<String, Object> param = new HashMap<>();
        param.put("materCode", materCode);
        List<MaterialBaseEntity> materialBases = materialBaseDao.queryList(param);
        return CollectionUtil.isNotEmpty(materialBases) ? materialBases.get(0) : null;
    }
}
